package com.topisv.tms.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.CustomerAreaGroup;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.WarehouseArea;
import com.topisv.tms.repository.AreaDao;
import com.topisv.tms.repository.AreaGroupDao;
import com.topisv.tms.repository.WarehouseAreaDao;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.base.BaseService;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.vo.RestAreaGroupVo;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;

@Component
@Transactional(readOnly = true)
public class AreaGroupService extends BaseService {

    @Autowired
    private AreaGroupDao areaGroupDao;
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private CustomerAreaGroupService customerAreaGroupService;
    @Autowired
    private WarehouseAreaDao warehouseAreaDao;

    private static final Logger logger = LoggerFactory.getLogger(AreaGroupService.class);

    public AreaGroup getAreaGroup(Long id) {
        logger.info("getAreaGroup: id=" + id);
        return areaGroupDao.findOne(id);
    }

    public List<AreaGroup> findAll() {
        return (List<AreaGroup>) areaGroupDao.findAll();
    }

    @Transactional(readOnly = false)
    public void saveAreaGroup(AreaGroup entity) {
        logger.info("saveAreaGroup: groupname=" + entity.getGroupName());
        areaGroupDao.save(entity);
    }

    public AreaGroup findByGroupCode(String groupCode) {
        return areaGroupDao.findByGroupCode(groupCode);
    }

    public AreaGroup findOne(Long groupId) {
        return areaGroupDao.findOne(groupId);
    }

    @Transactional(readOnly = false)
    public void deleteAreaGroup(Long id) {
        logger.info("deleteAreaGroup: id=" + id);
        areaGroupDao.delete(id);
    }

    public List<Area> getAreaByAreaGroupId(Long areagroupid) {
        return (List<Area>) areaDao.findByAreaGroupId(areagroupid);
    }

    /**
     * 分页显示表内所有行.
     */
    public Page<AreaGroup> getAreaGroup(Map<String, Object> filterParams, int pageNumber, int pageSize, String sortType) {
        PageRequest pageRequest = buildAreaGroupPageRequest(pageNumber, pageSize, sortType);
        Specification<AreaGroup> spec = buildSpecification(filterParams);
        return areaGroupDao.findAll(spec, pageRequest);
    }

    /**
     * 创建分页请求.
     */
    private PageRequest buildAreaGroupPageRequest(int pageNumber, int pageSize, String sortType) {
        Sort sort = null;
        if (null != sortType) {
            String[] sorts = sortType.split("_");

            if (sortType.endsWith("desc")) {
                sort = new Sort(Direction.DESC, sorts[0]);
            } else if (sortType.endsWith("asc")) {
                sort = new Sort(Direction.ASC, sorts[0]);
            }
        }
        return new PageRequest(pageNumber - 1, pageSize, sort);
    }

    /**
     * 创建动态查询条件组合.
     */
    private Specification<AreaGroup> buildSpecification(Map<String, Object> filterParams) {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        Specification<AreaGroup> spec = DynamicSpecifications.bySearchFilter(filters.values(), AreaGroup.class);
        return spec;
    }

    public void setAreaGroupDao(AreaGroupDao areaGroupDao) {
        this.areaGroupDao = areaGroupDao;
    }

    public void setAreaDao(AreaDao areaDao) {
        this.areaDao = areaDao;
    }

    public List<AreaGroup> loadByCustomerCode(String customerCode) {
        return this.areaGroupDao.loadByCustomerCode(customerCode);
    }

    /**
     * 查询
     * 
     * @param warehouseType
     *            仓库类型
     * @return
     */
    public List<AreaGroup> loadByWarehouseType(String warehouseType) {
        return this.areaGroupDao.loadByWarehouseType(warehouseType);
    }

    /**
     * 查询商家仓库+PAIU仓库
     * 
     * @param customerCode
     * @return
     */
    public List<AreaGroup> loadByCustomerCodeAndPaiu(String customerCode) {

        // 商家仓库
        List<AreaGroup> customerWarehouseList = this.loadByCustomerCode(customerCode);

        // if(!customerCode.equals("paiu")){
        // //paiu仓库
        // List<AreaGroup> paiuWarehouseList=this.loadByWarehouseType("paiu");
        // customerWarehouseList.addAll(paiuWarehouseList);
        // }

        return customerWarehouseList;
    }

    public List<AreaGroup> loadAreaGroupByAuthority(String customerCode) {
        List<AreaGroup> areagroupList = null;
        if (StringUtils.isBlank(customerCode)) {
            return null;
        }
        areagroupList = new ArrayList<AreaGroup>();
        List<CustomerAreaGroup> customerAreaGroups = this.customerAreaGroupService.findByCustomerCode(customerCode);
        for (CustomerAreaGroup cag : customerAreaGroups) {
            AreaGroup areaGroup = this.areaGroupDao.findByGroupCode(cag.getAreaGroupCode());
            areagroupList.add(areaGroup);
        }

        return areagroupList;
    }

    /**
     * 根据用户权限,获取仓库信息
     * 
     * @param user
     * @return
     * @throws Exception
     */
    public List<AreaGroup> loadAreaGroupByAuthority(ShiroUser user, String customerCode) {

        String userType = user.userType;
        List<AreaGroup> areagroupList = null;
        String lists = user.areagroups;

        if (StringUtils.isBlank(lists)) {
            return null;
        }

        String[] list = lists.split(":");
        List<AreaGroup> tempAreaGroups = new ArrayList<AreaGroup>();
        // 商家仓库
        if (StatusEnums.user_type_customer.getStatus().equals(userType)) {
            areagroupList = this.loadByCustomerCode(customerCode);
        }
        // 派友网点
        else if (StatusEnums.user_type_paiu.getStatus().equals(userType)) {
            areagroupList = new ArrayList<AreaGroup>();
            RestCustomersAreagroupVo restCustomersAreagroupVo = this.customerAreaGroupService.getRestCustomersAreagroupVo(customerCode);
            List<RestAreaGroupVo> restAreaGroupVoList = restCustomersAreagroupVo.getRestAreaGroupDtos();
            for (RestAreaGroupVo restAreaGroupVo : restAreaGroupVoList) {
                String areagroupCode = restAreaGroupVo.getAreagroupCode();
                AreaGroup areagroup = this.findByGroupCode(areagroupCode);
                areagroupList.add(areagroup);
            }
        }
        for (AreaGroup a : areagroupList) {
            for (String l : list) {
                if (l.equals(a.getGroupCode())) {
                    tempAreaGroups.add(a);
                }
            }
        }
        if (tempAreaGroups.isEmpty()) {
            tempAreaGroups = areagroupList;
        }
        return tempAreaGroups;
    }

    public List<AreaGroup> findByAreaGroups(String areaGroups) {
        if (StringUtils.isBlank(areaGroups)) {
            return null;
        }
        String[] areaGroupArray = areaGroups.split(":");
        List<AreaGroup> areagroupList = new ArrayList<AreaGroup>();
        for (String groupCode : areaGroupArray) {
            areagroupList.add(findByGroupCode(groupCode));
        }
        return areagroupList;
    }

    /**
     * 分页查询放法
     * 
     * @param
     * @return
     * @throws @author
     *             <a href=mailto:libin@nryuncang.com>libin</a>
     * @version 1.0.0
     */
    public Page<AreaGroup> pageAreaGroups(QueryParamHolder paramHolder) {
        return findByJson(paramHolder, areaGroupDao, AreaGroup.class);
    }

    public List<AreaGroup> loadByCustomerCodeAndWarehouseType(String customerCode, String warehouseType) {
        return areaGroupDao.loadByCustomerCodeAndWarehouseType(customerCode, warehouseType);
    }
    
}
